package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Resource
    private WeChatProperties weChatProperties;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private AddressBookMapper addressBookMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private DishMapper dishMapper;

    @Resource
    private SetmealMapper setmealMapper;

    @Resource
    private WebSocketServer webSocketServer;


    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);//查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.queryByCondition(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(UUID.randomUUID()));
        orders.setStatus(1);
        orders.setPayStatus(0);
        orders.setOrderTime(LocalDateTime.now());
        BeanUtils.copyProperties(addressBook, orders);
        String provinceName = addressBook.getProvinceName();
        String cityName = addressBook.getCityName();
        String districtName = addressBook.getDistrictName();
        String detail = addressBook.getDetail();
        StringBuilder fullAddressBuilder = new StringBuilder();
        fullAddressBuilder.append(provinceName)
                .append(cityName)
                .append(districtName)
                .append(detail);
        orders.setAddress(fullAddressBuilder.toString());
        User user = userMapper.getById(userId);
        orders.setUserName(user.getName());
        orderMapper.insert(orders);
        //查询当前用户的购物车数据
        List<OrderDetail> orderDetails = new ArrayList();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        return OrderSubmitVO.builder().id(orders.getId()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).orderTime(orders.getOrderTime()).build();
    }

    @Override
    public Orders paySuccess(String orderNumber) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(orderNumber);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号" + orderNumber);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return ordersDB;
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.queryByCondiction(ordersPageQueryDTO);
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(order.getId());
            orderVO.setOrderDetailList(orderDetailList);
            //还少一个字符串，菜品信息
            List<String> dishInfoList = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                Long dishId = orderDetail.getDishId();
                if (dishId != null) {
                    //代表是一个菜品
                    Dish dish = dishMapper.getById(dishId);
                    dishInfoList.add(dish.getName() + "*" + orderDetail.getNumber());
                } else {
                    //代表是一个套餐
                    Setmeal setmeal = setmealMapper.getById(orderDetail.getSetmealId());
                    dishInfoList.add(setmeal.getName() + "*" + orderDetail.getNumber());
                }
            }
            orderVO.setOrderDishes(StringUtils.join(dishInfoList, ";"));
            orderVOS.add(orderVO);
        }
        return new PageResult(orders.getTotal(), orderVOS);
    }

    @Override
    public OrderVO queryDetailsById(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void update(Orders orders) {
        orderMapper.update(orders);
    }

    @Override
    public OrderStatisticsVO getStatistics() {
        Map map = new HashMap<>();
        map.put("status",Orders.TO_BE_CONFIRMED);
        Integer TO_BE_CONFIRMED = orderMapper.countByMap(map);
        map = new HashMap<>();
        map.put("status",Orders.CONFIRMED);
        Integer CONFIRMED = orderMapper.countByMap(map);
        map = new HashMap<>();
        map.put("status",Orders.DELIVERY_IN_PROGRESS);
        Integer DELIVERY_IN_PROGRESS = orderMapper.countByMap(map);
        return new OrderStatisticsVO(TO_BE_CONFIRMED,CONFIRMED,DELIVERY_IN_PROGRESS);
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setId(id);
        orderMapper.update(orders);
    }

    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public PageResult listHistory(int page, int pageSize, Integer status) {
            // 设置分页
            PageHelper.startPage(page, pageSize);

            OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
            ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
            ordersPageQueryDTO.setStatus(status);

            // 分页条件查询
            Page<Orders> ordersPage = orderMapper.queryByCondiction(ordersPageQueryDTO);

            List<OrderVO> list = new ArrayList();

            // 查询出订单明细，并封装入OrderVO进行响应
            if (ordersPage != null && ordersPage.getTotal() > 0) {
                for (Orders orders : ordersPage) {
                    Long orderId = orders.getId();// 订单id

                    // 查询订单明细
                    List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);

                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(orders, orderVO);
                    orderVO.setOrderDetailList(orderDetails);

                    list.add(orderVO);
                }
            }
            return new PageResult(ordersPage.getTotal(), list);
        }

    @Override
    @Transactional
    public void repetition(Long id) {
        /*
        * 将原来的订单详细数据插入到购物车
        * */
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public OrderVO view(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void userCancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
